/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-03-03 11:59:11
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-14 13:53:31
 */

import {
  userAPI
} from "../../../api/index";

// pages/login/verifyCode.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

    inputLen: 4,
    iptValue: "",
    isFocus: true,
    time: 60,
    phone: ''
  },

  onFocus: function (e) {
    var that = this;
    that.setData({
      isFocus: true
    });
  },
  reSendSms() {
    if (this.data.time) return
    userAPI.sendSms({
      phone: this.data.phone
    }).then(res => {
      this.setData({
        time: 60
      })
      this.setTime()
      wx.showToast({
        title: res.data.message,
        icon: 'none'
      })
    })
  },
  setValue: function ({
    detail: {
      value: iptValue
    }
  }) {
    var that = this;
    that.setData({
      iptValue
    });
    if (iptValue.length === 4) {
      // 执行登录操作
      userAPI.loginByPhone({
        phone: this.data.phone,
        code: this.data.iptValue
      }).then(({code,data}) => {
          wx.showToast({
            title: data.message,
            icon:'none'
          })
        if (code === 200) {
          wx.setStorage({
            data: data.token,
            key: 'token',
          })
          wx.setStorage({
            data: data && data.userInfo,
            key: 'userInfo',
          })
          wx.navigateBack({
            delta: 2
          })
        } 
      })
    }
  },
  setTime() {
    let {
      time
    } = this.data
    const timer = setInterval(() => {
      if (time === 1) {
        clearInterval(timer)
      }
      this.setData({
        time: --time,
      })
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var appInst =  getApp();
    appInst.setTitle('填写验证码')
    // 倒计时
    this.setTime()
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('params', ({
      phone
    }) => {
      const mask_phone = phone.slice(0, 4) + '****' + phone.slice(7, 11)
      this.setData({
        phone,
        mask_phone
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})